package com.caipiao.crawler.football;

import com.alibaba.fastjson.JSON;
import com.caipiao.crawler.daletou.DaletouResultPage;
import com.caipiao.crawler.mapper.LotteryFootballMapper;
import com.caipiao.crawler.model.LotteryFootball;
import com.caipiao.util.DBTools;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by adminitrator on 2018/7/28.
 */
public class FootballDetailPipeline implements Pipeline {

    private static Log log = LogFactory.getLog(FootballDetailPipeline.class);

    @Override
    public synchronized void process(ResultItems resultItems, Task task) {
        String details = resultItems.get("details");
        String mid = resultItems.get("mid");
        log.info("pipe process:" + Thread.currentThread().getId());
        if(mid == null) {
            return;
        }
        Map map = new HashMap();
        map.put("details",details);
        map.put("mid",mid);
        commit(map);
    }

    public void commit(Map map) {
        log.info("----------footballDetailPipeline commit 开始-----------");
        //TODO 写数据库，需要判断不存在的情况才写入
        SqlSession session = DBTools.getSession();
        LotteryFootballMapper mapper = session.getMapper(LotteryFootballMapper.class);
        mapper.updateByMid(map);
        session.commit();
        //TODO 如果第一次写入，触发更新判断是否中奖的逻辑

        session.close();
        log.info("----------footballDetailPipeline commit 结束-----------");
    }

}
